package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.PageResult;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.MyCourseTableParams;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 选课相关接口实现
 * @author 冯佳鑫 又菜又爱学
 * @version 1.0
 * @DATE now()
 */
@Service
public class MyCourseTablesServiceimpl implements MyCourseTablesService {
    @Autowired
    XcChooseCourseMapper xcChooseCourseMapper;
    @Autowired
    XcCourseTablesMapper xcCourseTablesMapper;
    @Autowired
    ContentServiceClient contentServiceClient;

    //添加选课和我的课程
    @Transactional
    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        XcChooseCourseDto xcChooseCourseDto_ = new XcChooseCourseDto();
        if (coursepublish==null){
            throw new XueChengPlusException("课程不存在");
        }
        //选课调用内容管理的课程发布信息，并查询课程的收费规则======
        String charge = coursepublish.getCharge();

        if (charge.equals("201000")){
            //如果是免费课程，插入选课表和我的课程表======
            XcChooseCourse xcChooseCourse = addFreeCoruse(userId, coursepublish);
            BeanUtils.copyProperties(xcChooseCourse,xcChooseCourseDto_);
            XcCourseTables xcCourseTables = addCourseTabls(xcChooseCourse);
        }
        else {
            //如果是收费的话，插入选课表
            XcChooseCourse xcChooseCourse = addChargeCoruse(userId, coursepublish);
            BeanUtils.copyProperties(xcChooseCourse,xcChooseCourseDto_);
        }
        //判断学生的学习资格并设置
        XcCourseTablesDto learningStatus = getLearningStatus(userId, courseId);
        xcChooseCourseDto_.setLearnStatus(learningStatus.getLearnStatus());

        return xcChooseCourseDto_;
    }

    //添加免费课程,免费课程加入选课记录表、我的课程表
    public XcChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {
        Long id = coursepublish.getId();
        //先判断选课表是否已经存在且选课状态是否成功

        LambdaQueryWrapper<XcChooseCourse> wrapper = new LambdaQueryWrapper<XcChooseCourse>().eq(XcChooseCourse::getCourseId, id).
                eq(XcChooseCourse::getUserId, userId).eq(XcChooseCourse::getOrderType, "700001")//选课类型：免费
                .eq(XcChooseCourse::getStatus, "701001");//选课状态:成功
        //选课表可能会有多条重复，因为字段没有约束
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(wrapper);
        //如果选课表已经存在,则取出一条返回
        if (xcChooseCourses.size()>0){
            return xcChooseCourses.get(0);
        }
        //向选课记录表写数据
        XcChooseCourse xcChooseCourse = new XcChooseCourse();

        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCoursePrice(0f);//免费课程价格为0
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700001");//免费课程
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setStatus("701001");//选课成功

        xcChooseCourse.setValidDays(365);//免费课程默认365
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        //插入到选课表中
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert<0){
            throw new XueChengPlusException("插入到选课表失败");
        }
        return xcChooseCourse;
    }
    //添加到我的课程表,是基于选课表
    public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse){
      //判断选课表选课状态是否成功
        String status = xcChooseCourse.getStatus();
        if (!status.equals("701001")){
            throw new XueChengPlusException("选课未成功，无法添加到课程表");
        }
        //查询我的课程表是否存在
        XcCourseTables courseTabls = getCourseTabls(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
        if (courseTabls!=null){
            return courseTabls;
        }
        XcCourseTables xcCourseTables = new XcCourseTables();
        BeanUtils.copyProperties(xcChooseCourse,xcCourseTables);
        xcCourseTables.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTables.setUserId(xcChooseCourse.getUserId());
        xcCourseTables.setCourseId(xcChooseCourse.getCourseId());
        xcCourseTables.setCompanyId(xcChooseCourse.getCompanyId());
        xcCourseTables.setCourseName(xcChooseCourse.getCourseName());
        xcCourseTables.setCreateDate(LocalDateTime.now());
        xcCourseTables.setValidtimeStart(xcChooseCourse.getValidtimeStart());
        xcCourseTables.setValidtimeEnd(xcChooseCourse.getValidtimeEnd());
        xcCourseTables.setCourseType(xcChooseCourse.getOrderType());
        int insert = xcCourseTablesMapper.insert(xcCourseTables);
        if (insert<0){
            throw new XueChengPlusException("插入到我的课程表失败");
        }

        return xcCourseTables;
    }

    //添加收费课程
    public XcChooseCourse addChargeCoruse(String userId,CoursePublish coursepublish){
        Long id = coursepublish.getId();
        //先判断选课表是否已经存在且选课状态是否成功

        LambdaQueryWrapper<XcChooseCourse> wrapper = new LambdaQueryWrapper<XcChooseCourse>().eq(XcChooseCourse::getCourseId, id).
                eq(XcChooseCourse::getUserId, userId).eq(XcChooseCourse::getOrderType, "700002")//选课类型：收费
                .eq(XcChooseCourse::getStatus, "701002");//选课状态:待支付
        //选课表可能会有多条重复，因为字段没有约束
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(wrapper);
        //如果选课表已经存在,则取出一条返回
        if (xcChooseCourses.size()>0){
            return xcChooseCourses.get(0);
        }
        //向选课记录表写数据
        XcChooseCourse xcChooseCourse = new XcChooseCourse();

        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());//免费课程价格为0
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700002");//收费课程
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setStatus("701002");//待支付

        xcChooseCourse.setValidDays(365);//免费课程默认365
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        //插入到选课表中
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert<0){
            throw new XueChengPlusException("插入到选课表失败");
        }
        return xcChooseCourse;
    }
   //查询我的课程是否存在
    XcCourseTables getCourseTabls(String userId,Long courseId){
        LambdaQueryWrapper<XcCourseTables> eq = new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getCourseId, courseId)
                .eq(XcCourseTables::getUserId, userId);
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(eq);
        return xcCourseTables;
    }
    /**
     * @description 判断学习资格
     * @param userId
     * @param courseId
     * @return XcCourseTablesDto 学习资格状态 [{"code":"702001","desc":"正常学习"},{"code":"702002","desc":"没有选课或选课后没有支付"},{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
     * @author Mr.M
     * @date 2022/10/3 7:37
     */

    public XcCourseTablesDto getLearningStatus(String userId, Long courseId){
        //查询我的课程表
        XcCourseTables xcCourseTables = getCourseTabls(userId, courseId);
        if(xcCourseTables==null){
            XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
            //没有选课或选课后没有支付
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }
        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);
        //是否过期,true过期，false未过期
        boolean isExpires = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if(!isExpires){
            //正常学习
            xcCourseTablesDto.setLearnStatus("702001");
            return xcCourseTablesDto;

        }else{
            //已过期
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        }


    }

    /**
     * 查询课程
     * @param params
     * @return
     */
    @Override
    public PageResult<XcCourseTables> mycoursetable(MyCourseTableParams params) {
        //拿到当前页，每页展示条数
        int pageNo = params.getPage();
        int size = params.getSize();
        String userId = params.getUserId();
        //分页查询
        Page<XcCourseTables> page = new Page<>();
        page.setSize(size);
        page.setCurrent(pageNo);
        LambdaQueryWrapper<XcCourseTables> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcCourseTables::getUserId,userId);
        IPage<XcCourseTables> xcCourseTablesIPage = xcCourseTablesMapper.selectPage(page,queryWrapper);
        List<XcCourseTables> XcCourseTableslist = xcCourseTablesIPage.getRecords();
        //将数据封装到PageResult返回给前端
        PageResult pageResult = new PageResult();
        pageResult.setItems(XcCourseTableslist);
        pageResult.setCounts(xcCourseTablesIPage.getTotal());
        pageResult.setPage(pageNo);
        pageResult.setPageSize(size);
        return pageResult;
    }
}
